/**
 * Created by chuxin on 2017/2/10.
 */
import Vue from "vue";
import Vuex from "vuex";
import {fetch_songs, fetch_song, fetch_lyric} from "./api.js";

Vue.use(Vuex);

let store = new Vuex.Store({
    state: {
        hideWelcome: true,
        songs: [],
        song: null,
        playing: false,
        lyricArr: [],
        lrcTimeArr: [],
        lrcMarginTop: 0,
    },
    getters: {},
    actions: {
        fetch_songs(context, options) {
            let promise = fetch_songs(options);
            promise.then(resp => {
                console.log(resp);
                context.commit("songsLoaded", {songs: resp.data.result.songs});
            }, resp => {
            });
            return promise;
        },
        fetch_song(context, musicId) {
            let promise = fetch_song(musicId);
            promise.then(resp => {
                console.log(resp);
                context.commit('songLoaded', {song: resp.data.songs[0]});
            });
            return promise;
        },
        fetch_lyric(context, musicId) {
            let promise = fetch_lyric(musicId);
            promise.then(resp => {
                console.log(resp);
                context.commit('lyricLoaded', {lyric: resp.data.lrc.lyric})
            });
            return promise;
        }
    },
    mutations: {
        hideWelcome(state){
            state.showWelcome = false;
        },
        changePlaying(state, isPlaying){
            state.playing = isPlaying;
        },
        songsLoaded(state, payload) {
            state.songs = payload.songs;
        },
        songLoaded(state, payload){
            state.song = payload.song;
        },
        lyricLoaded(state, payload){
            let arr = payload.lyric.split('\n');
            state.lyricArr = convertLrcArr(arr);
            state.lrcTimeArr = state.lyricArr.map((v) => {
                return v['time'];
            });
        },
        changeLrcMargin(state, lrcMarginTop) {
            state.lrcMarginTop = lrcMarginTop;
        }
    }
});

function convertLrcArr(arr) {
    let lrcArr = [];
    let duration = 0;
    console.log(arr.length);
    for (let i = 0; i < arr.length - 1; i++) {
        let item = arr[i];
        let lrcObj = {};
        let timeStr = item.match("\\[(.+?)\\]")[1];

        //declude not time
        if (/[^0-9\.\:]/.test(timeStr)) {
            continue;
        }
        let timeArr = timeStr.split(":");
        let time = parseInt(timeArr[0]) * 60 + parseFloat(timeArr[1]);

        lrcObj.selected = false;
        lrcObj.show = true;

        lrcObj.time = time;
        lrcObj.lrc = item.replace(new RegExp(/(\.\d{2,3})/g), '');
        lrcArr.push(lrcObj);
    }
    return lrcArr;
}

export default store;